package com.p2p.terminal.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.p2p.account.po.Agent;
import com.p2p.account.service.AgentService;
import com.p2p.common.constants.Message;
import com.p2p.common.utils.ExcelUtil;
import com.p2p.common.utils.ResMessage;
import com.p2p.terminal.po.P2pIp;
import com.p2p.terminal.service.IpService;
import com.p2p.terminal.vo.IpCondition;

@RestController
@RequestMapping(value = "terminal")
public class IpController {

	@Autowired
	private IpService ipService;

	@Autowired
	private AgentService agentService;

	/**
	 * 查询终端信息接口
	 *
	 * @return
	 */
	@RequestMapping(value = "selectIpData", method = RequestMethod.POST)
	public ResMessage<P2pIp> selectIpData(@RequestBody IpCondition condition) {

		ResMessage<P2pIp> selectIpData = ipService.selectIpData(condition);
		return selectIpData;
	}

	/**
	 * 导出数据
	 *
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "exportIpData", method = RequestMethod.GET)
	public Message exportIpData(HttpServletRequest request, HttpServletResponse response) throws IOException {

		List<P2pIp> selectIpData = ipService.exportIpData(request);

		String fileName = "ip数据" + System.currentTimeMillis();

		List<Map<String, Object>> list = tempCreateExcelRecord(selectIpData);
		// 列名
		String columnNames[] = { "日期", "编号", "代理", "种类", "外网IP", "路由Mac", "有效提交", "总终端", "无效终端", "异常终端", "特殊终端", "启动次数",
				"启动成功", "运行30", "运行60", "挖矿30", "挖矿60", "忙次数" };
		// 对应map的key
		String keys[] = { "dateTime", "agentId", "agentName", "coinType", "outernetIp", "cmac", "validSubmitCount",
				"terminalTotalCount", "terminalInvalidCount", "terminalErrorCount", "terminalSpecialCount",
				"startTotalCount", "startSuccessCount", "run30", "run60", "mining30", "mining60", "busyCount" };
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		try {
			Workbook workbook = ExcelUtil.createWorkBook(list, keys, columnNames);
			workbook.write(os);
			// test1(workbook);
		} catch (IOException e) {
			e.printStackTrace();
		}
		byte[] content = os.toByteArray();
		InputStream is = new ByteArrayInputStream(content);
		// 设置response参数，可以打开下载页面
		response.reset();
		response.setContentType("application/vnd.ms-excel;charset=utf-8");
		response.setHeader("Content-Disposition",
				"attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
		ServletOutputStream out = response.getOutputStream();
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			bis = new BufferedInputStream(is);
			bos = new BufferedOutputStream(out);
			byte[] buff = new byte[40960];
			int bytesRead;
			// Simple read/write loop.
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
		} catch (final IOException e) {
			throw e;
		} finally {
			if (bis != null)
				bis.close();
			if (bos != null)
				bos.close();
		}
		return null;
	}

	private List<Map<String, Object>> tempCreateExcelRecord(List<P2pIp> projects) {
		List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("sheetName", "sheet1");
		listmap.add(map);
		P2pIp item = null;
		for (int j = 0; j < projects.size(); j++) {
			item = projects.get(j);

			Map<String, Object> mapValue = new HashMap<String, Object>();
			mapValue.put("dateTime", item.getDateTime());
			mapValue.put("agentId", item.getAgentId());
			mapValue.put("agentName", item.getAgentName());
			mapValue.put("coinType", item.getCoinType());
			mapValue.put("outernetIp", item.getOuternetIp());
			mapValue.put("cmac", item.getCmac());
			mapValue.put("validSubmitCount", item.getValidSubmitCount());
			mapValue.put("terminalTotalCount", item.getTerminalTotalCount());
			mapValue.put("terminalInvalidCount", item.getTerminalInvalidCount());
			mapValue.put("terminalErrorCount", item.getTerminalErrorCount());
			mapValue.put("terminalSpecialCount", item.getTerminalSpecialCount());
			mapValue.put("startTotalCount", item.getStartTotalCount());
			mapValue.put("startSuccessCount", item.getStartSuccessCount());
			mapValue.put("run30", item.getRun30());
			mapValue.put("run60", item.getRun60());
			mapValue.put("mining30", item.getMining30());
			mapValue.put("mining60", item.getMining60());
			mapValue.put("busyCount", item.getBusyCount());
			listmap.add(mapValue);
		}
		return listmap;
	}

	/**
	 * 获取代理商列表
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "selectAgent", method = RequestMethod.GET)
	public Message selectAgent(HttpServletRequest request,HttpServletResponse response) {
		List<Agent> selectList = agentService.selectList(new EntityWrapper<Agent>().eq("status", 1));
		
		
		return new Message(200, "ok", selectList);
	}

}
